package com.ljh.onlinetest.configuration.spring.security;

import com.ljh.onlinetest.domain.User;
import com.ljh.onlinetest.domain.enums.RoleEnum;
import com.ljh.onlinetest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * @author ljh
 * @ClassName RestDetailsServiceImpl.java
 * @createTime 2022年01月04日
 * 验证通过之后,第二、三...请求，会调用此类
 */
@Component
public class RestDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;

    @Autowired
    public RestDetailsServiceImpl(UserService userService) {
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.getUserByUserName(username);
        if (user == null) {
            throw new UsernameNotFoundException("Username not found");
        }

        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        grantedAuthorities.add(new SimpleGrantedAuthority(RoleEnum.formCode(user.getRole()).getRoleName()));

        return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getPassword(),grantedAuthorities);
    }
}
